import { useEffect, useState } from "react";
import Navigate from "../components/Navigate.jsx";
import "./Management.css";
import { listPostsService, deletePostService, fetchPinnedPostService,
  updatePostService, lockPostService
 } from "../api/CommunityApi.jsx";

const forums = [
  { id: 1, name: "动漫" },
  { id: 2, name: "面经" },
  { id: 3, name: "游戏" },
  { id: 4, name: "其它" }
];
const types = [
  { id: 1, name: "普通" },
  { id: 2, name: "精华" },
  { id: 3, name: "悬赏" }
];
const statusOptions = [
  { value: 1, label: "正常" },
  { value: 2, label: "审核中" },
  { value: 3, label: "已锁定" }
];
const timeRanges = [
  { value: "", label: "全部" },
  { value: "day", label: "一天内" },
  { value: "week", label: "一周内" },
  { value: "month", label: "一个月内" }
];
const sortOptions = [
  { value: "createdTime", label: "按时间排序" },
  { value: "commentCount", label: "按评论数排序" },
  { value: "viewCount", label: "按浏览数排序" }
];
const pageSizeOptions = [10, 20, 50];

function PostManagement() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [activeTab, setActiveTab] = useState("normal"); // normal | pinned
  const [searchData, setSearchData] = useState({
    forumIds: [1,2,3,4], // 改为数组支持多选
    keyword: "",
    author: "",
    type: '', // 不传：全部，1: 普通, 2: 精华, 3: 悬赏
    timeRange: "", //不传：全部，day week month
    sortBy: "createdTime", // createdTime, commentCount, viewCount
    isHot: false, // 是否只显示热门帖子
    page: 1, // 当前页码
    pageSize: 10, // 每页显示数量
  });
  const [deleteId, setDeleteId] = useState(null);
  const [lockId, setLockId] = useState(null); 
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showLockModal, setShowLockModal] = useState(false);
  const [viewPost, setViewPost] = useState(null); // 当前查看的帖子
  const [showViewModal, setShowViewModal] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState({
    forumId: "",
    title: "",
    content: "",
    isPinned: 0,
    type: "",
  });

  // 查询帖子
  const fetchPosts = async () => {
    setLoading(true);
    try {
      const response = await listPostsService(searchData);
      if (response.status === 200) {
        setPosts(response.data.postList || []);
        setPagination({
          current: searchData.page || 1,
          pageSize: searchData.pageSize || 10,
          total: response.data.total || 0,
        });
      }
    } catch (e) {
      setPosts([]);
      setPagination((prev) => ({ ...prev, total: 0 }));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, [searchData]);

  const fetchPinnedPosts = async (forumId) => {
    setLoading(true);
    try {
      const response = await fetchPinnedPostService(forumId || 1); // 默认查询动漫板块的置顶帖子
      if (response.status === 200) {
        setPosts(response.data || []);
      }
    } catch (e) {
      setPosts([]);
    } finally {
      setLoading(false);
    }
  }

  // 切换tab
  const handleTabChange = (tab) => {
    setActiveTab(tab);
    if (tab === "normal") {
      setSearchData((prev) => ({
        ...prev,
        forumIds: [1,2,3,4],
        page: 1,
      }));
    } else {
      fetchPinnedPosts(1);
    }
  };

// 板块多选/单选
  const handleForumChange = (forumId) => {
    if (activeTab === "pinned") {
      fetchPinnedPosts(forumId);
    } else {
      setSearchData((prev) => {
        const newForumIds = prev.forumIds.includes(forumId)
          ? prev.forumIds.filter(id => id !== forumId)
          : [...prev.forumIds, forumId];
        return {
          ...prev,
          forumIds: newForumIds,
          page: 1
        };
      });
    }
  };

  // 重置
  const handleReset = () => {
    if (activeTab === "pinned") {
      fetchPinnedPosts(1);
    } else {
        setSearchData({
        forumIds: [1,2,3,4], 
        keyword: "",
        author: "",
        type: '', 
        timeRange: "", 
        sortBy: "createdTime", 
        isHot: false,
        page: 1,
        pageSize: 10,
      });
    }    
  };

  // 打开查看弹窗
  const handleView = (post) => {
    setViewPost(post);
    setEditForm({
      forumId: post.forumId,
      title: post.title,
      content: post.content,
      isPinned: post.isPinned,
      type: post.type,
    });
    setIsEditing(false);
    setShowViewModal(true);
  };

  // 编辑表单变更
  const handleEditFormChange = (e) => {
    const { name, value, type, checked } = e.target;
    setEditForm((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? (checked ? 1 : 0) : value,
    }));
  };

  // 保存编辑
  const handleSaveEdit = async () => {
    try {
      const postData = {
        id: viewPost.id,
        forumId: editForm.forumId,
        title: editForm.title,
        content: editForm.content,
        isPinned: editForm.isPinned,
        type: editForm.type,
      };
      await updatePostService(postData);
      setShowViewModal(false);
      setIsEditing(false);
      fetchPosts();
    } catch {
      alert("保存失败，请重试！");
    }
  };

  const confirmLock = async () => {
    if (lockId === null) return;
    try {
      await lockPostService(lockId);
      fetchPosts();
      setShowLockModal(false);
      setLockId(null);
    } catch {
      alert("锁定失败！");
    }
  }

  // 分页
  const handlePageChange = (page) => {
    setSearchData((prev) => ({
      ...prev,
      page: page,
    }));
  };

  const handlePageSizeChange = (pageSize) => {
    setSearchData((prev) => ({
      ...prev,
      pageSize: pageSize,
      page: 1,
    }));
  };

  // 删除
  const handleDelete = async () => {
    if (!deleteId) return;
    try {
      await deletePostService(deleteId);
      setShowDeleteModal(false);
      setDeleteId(null);
      fetchPosts();
    } catch {
      setShowDeleteModal(false);
      setDeleteId(null);
      alert("删除失败");
    }
  };

  // 格式化时间
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN");
  };

  // 分页渲染
  const renderPagination = () => {
    const totalPages = Math.ceil(pagination.total / pagination.pageSize);
    const pages = [];
    let startPage = Math.max(1, pagination.current - 2);
    let endPage = Math.min(totalPages, pagination.current + 2);

    if (endPage - startPage < 4) {
      if (startPage === 1) {
        endPage = Math.min(totalPages, startPage + 4);
      } else if (endPage === totalPages) {
        startPage = Math.max(1, endPage - 4);
      }
    }

    if (startPage > 1) {
      pages.push(
        <button key="1" className="pagination-btn" onClick={() => handlePageChange(1)}>
          1
        </button>
      );
      if (startPage > 2) {
        pages.push(
          <span key="start-ellipsis" className="page-ellipsis">
            ...
          </span>
        );
      }
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          className={`pagination-btn ${pagination.current === i ? "active" : ""}`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>
      );
    }

    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        pages.push(
          <span key="end-ellipsis" className="page-ellipsis">
            ...
          </span>
        );
      }
      pages.push(
        <button key={totalPages} className="pagination-btn" onClick={() => handlePageChange(totalPages)}>
          {totalPages}
        </button>
      );
    }
    return pages;
  };

  return (
    <div className="admin-layout">
      <Navigate activeItem="帖子管理" />
      <div className="main-content">
        <div className="management-container">
          <div className="header">
            <h2>帖子管理</h2>
          </div>

          {/* 标签切换 */}
          <div style={{ display: "flex", gap: 16, marginBottom: 24 }}>
            <div
              className={`tab-btn${activeTab === "normal" ? " tab-active" : ""}`}
              style={{
                padding: "8px 28px",
                borderRadius: 8,
                background: activeTab === "normal" ? "#667eea" : "#f3f4f6",
                color: activeTab === "normal" ? "#fff" : "#374151",
                fontWeight: 600,
                fontSize: 16,
                cursor: "pointer",
                border: "none",
                transition: "all 0.2s"
              }}
              onClick={() => handleTabChange("normal")}
            >
              普通帖
            </div>
            <div
              className={`tab-btn${activeTab === "pinned" ? " tab-active" : ""}`}
              style={{
                padding: "8px 28px",
                borderRadius: 8,
                background: activeTab === "pinned" ? "#667eea" : "#f3f4f6",
                color: activeTab === "pinned" ? "#fff" : "#374151",
                fontWeight: 600,
                fontSize: 16,
                cursor: "pointer",
                border: "none",
                transition: "all 0.2s"
              }}
              onClick={() => handleTabChange("pinned")}
            >
              置顶帖
            </div>
          </div>

          {/* 查询表单 */}
          <div className="search-form">
            {/* 论坛选择 */}
            <div className="form-group">
              <label>板块</label>
              {activeTab === "pinned" ? (
                <select
                  className="form-select"
                  value={searchData.forumIds[0]}
                  onChange={e => handleForumChange(Number(e.target.value))}
                >
                  {forums.map(forum => (
                    <option key={forum.id} value={forum.id}>{forum.name}</option>
                  ))}
                </select>
              ) : (
                <div className="multi-select-container">
                  <div className="checkbox-group">
                    {forums.map((forum) => (
                      <label key={forum.id} className="checkbox-item">
                        <input
                          type="checkbox"
                          checked={searchData.forumIds.includes(forum.id)}
                          onChange={() => handleForumChange(forum.id)}
                        />
                        <span className="checkbox-text">{forum.name}</span>
                      </label>
                    ))}
                  </div>
                  {searchData.forumIds.length > 0 && (
                    <div className="selected-tags">
                      {searchData.forumIds.map((id) => {
                        const forum = forums.find(f => f.id === id);
                        return (
                          <span key={id} className="selected-tag">
                            {forum.name}
                            <button type="button" onClick={() => handleForumChange(id)} className="remove-tag">
                              ×
                            </button>
                          </span>
                        );
                      })}
                    </div>
                  )}
                </div>
              )}
            </div>
            {/* 其他查询项 */}
            {activeTab === "normal" && (
              <>
                <div className="form-group">
                  <label>关键词</label>
                  <input
                    type="text"
                    className="form-input"
                    placeholder="请输入关键词"
                    value={searchData.keyword}
                    onChange={e => setSearchData({ ...searchData, keyword: e.target.value })}
                  />
                </div>
                <div className="form-group">
                  <label>作者</label>
                  <input
                    type="text"
                    className="form-input"
                    placeholder="请输入作者昵称"
                    value={searchData.author}
                    onChange={e => setSearchData({ ...searchData, author: e.target.value })}
                  />
                </div>
                <div className="form-group">
                  <label>帖子类型</label>
                  <select
                    className="form-select"
                    value={searchData.type}
                    onChange={e => setSearchData({ ...searchData, type: e.target.value })}
                  >
                    <option value="">全部</option>
                    {types.map(type => (
                      <option key={type.id} value={type.id}>{type.name}</option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label>时间范围</label>
                  <select
                    className="form-select"
                    value={searchData.timeRange}
                    onChange={e => setSearchData({ ...searchData, timeRange: e.target.value })}
                  >
                    {timeRanges.map(range => (
                      <option key={range.value} value={range.value}>{range.label}</option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label>排序方式</label>
                  <select
                    className="form-select"
                    value={searchData.sortBy}
                    onChange={e => setSearchData({ ...searchData, sortBy: e.target.value })}
                  >
                    {sortOptions.map(option => (
                      <option key={option.value} value={option.value}>{option.label}</option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label> </label>
                  <label className="checkbox-item hot-checkbox" style={{marginTop: "7px"}}>
                    <input
                      type="checkbox"
                      checked={searchData.isHot}
                      onChange={e => setSearchData({ ...searchData, isHot: e.target.checked })}
                    />
                    <span className="checkbox-text">仅显示热门帖</span>
                  </label>
                </div>
              </>
            )}
            <div className="form-group">
              <button className="btn btn-secondary" onClick={handleReset}>重置</button>
            </div>
          </div>

          {/* 帖子表格 */}
          <div className="table-container">
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>标题</th>
                  <th>板块</th>
                  <th>类型</th>
                  <th>作者</th>
                  <th>发布时间</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={8} style={{ textAlign: "center" }}>加载中...</td>
                  </tr>
                ) : posts.length === 0 ? (
                  <tr>
                    <td colSpan={8} style={{ textAlign: "center" }}>暂无数据</td>
                  </tr>
                ) : (
                  posts.map(post => (
                    <tr key={post.id}>
                      <td>
                        <span
                          className="post-id-link"
                          title="在新标签页中查看帖子"
                          onClick={() => window.open(`/community/${post.id}`, "_blank")}
                          onMouseOver={e => e.currentTarget.style.background = "#f0f4ff"}
                          onMouseOut={e => e.currentTarget.style.background = "transparent"}
                        >
                          {post.id}
                        </span>
                      </td>
                      <td>{post.title}</td>
                      <td>{forums.find(f => f.id === post.forumId)?.name || "-"}</td>
                      <td>{types.find(t => t.id === post.type)?.name || "-"}</td>
                      <td>{post.userName}</td>
                      <td>{formatDate(post.createdTime)}</td>
                      <td>
                        <span className={`status-badge ${post.status === 0 ? "status-normal" : "status-banned"}`}>
                          {statusOptions.find(s => s.value === post.status)?.label || "未知"}
                        </span>
                      </td>
                      <td>
                        <button
                          className="btn-action"
                          onClick={() => handleView(post)}
                        >
                          查看
                        </button>
                        <button
                          className="btn-action"
                          onClick={() => {
                            setLockId(post.id);
                            setShowLockModal(true);
                          }}
                        >
                          锁定
                        </button>
                        <button
                          className="btn-action delete"
                          onClick={() => {
                            setDeleteId(post.id);
                            setShowDeleteModal(true);
                          }}
                        >
                          删除
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* 查看/编辑弹窗 */}
          {showViewModal && viewPost && (
            <div className="modal-overlay" onClick={() => setShowViewModal(false)}>
              <div className="modal-content" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                  <h2>{isEditing ? "编辑帖子" : "帖子详情"}</h2>
                </div>
                <div className="modal-body">
                  {!isEditing ? (
                    <>
                      <div className="detail-section">
                        <h3 className="section-title">基本信息</h3>
                        <div className="detail-item">
                          <label className="detail-label">ID</label>
                          <div className="detail-value">{viewPost.id}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">标题</label>
                          <div className="detail-value">{viewPost.title}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">内容</label>
                          <div className="detail-value" style={{ whiteSpace: "pre-wrap" }}>{viewPost.content}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">板块</label>
                          <div className="detail-value">{forums.find(f => f.id === viewPost.forumId)?.name || "-"}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">类型</label>
                          <div className="detail-value">{types.find(t => t.id === viewPost.type)?.name || "-"}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">是否置顶</label>
                          <div className="detail-value">{viewPost.isPinned === 1 ? "是" : "否"}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">作者</label>
                          <div className="detail-value">{viewPost.userName}</div>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">发布时间</label>
                          <div className="detail-value">{formatDate(viewPost.createdTime)}</div>
                        </div>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="detail-section">
                        <h3 className="section-title">编辑帖子</h3>
                        <div className="detail-item">
                          <label className="detail-label">标题</label>
                          <input
                            className="edit-input"
                            name="title"
                            value={editForm.title}
                            onChange={handleEditFormChange}
                          />
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">内容</label>
                          <textarea
                            className="edit-input"
                            name="content"
                            value={editForm.content}
                            onChange={handleEditFormChange}
                            rows={5}
                          />
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">板块</label>
                          <select
                            className="edit-input"
                            name="forumId"
                            value={editForm.forumId}
                            onChange={handleEditFormChange}
                          >
                            {forums.map(f => (
                              <option key={f.id} value={f.id}>{f.name}</option>
                            ))}
                          </select>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">类型</label>
                          <select
                            className="edit-input"
                            name="type"
                            value={editForm.type}
                            onChange={handleEditFormChange}
                          >
                            {types.map(t => (
                              <option key={t.id} value={t.id}>{t.name}</option>
                            ))}
                          </select>
                        </div>
                        <div className="detail-item">
                          <label className="detail-label">是否置顶</label>
                          <label style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                            <input
                              type="checkbox"
                              name="isPinned"
                              checked={editForm.isPinned === 1}
                              onChange={handleEditFormChange}
                            />
                            <span>{editForm.isPinned === 1 ? "是" : "否"}</span>
                          </label>
                        </div>
                      </div>
                    </>
                  )}
                </div>
                <div className="modal-footer">
                  {isEditing ? (
                    <>
                      <button className="btn btn-primary" onClick={handleSaveEdit}>保存</button>
                      <button className="btn btn-secondary" onClick={() => setIsEditing(false)}>取消</button>
                    </>
                  ) : (
                    <>
                      <button className="btn btn-primary" onClick={() => setIsEditing(true)}>编辑</button>
                      <button className="btn btn-secondary" onClick={() => setShowViewModal(false)}>关闭</button>
                    </>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* 分页 */}
          {pagination.total > 0 && (
            <div className="pagination-container">
              <div className="pagination-info">共 {pagination.total} 条数据</div>
              <div className="pagination-controls">
                <button
                  onClick={() => handlePageChange(pagination.current - 1)}
                  disabled={pagination.current === 1}
                  className="pagination-btn"
                >
                  ‹
                </button>
                {renderPagination()}
                <button
                  onClick={() => handlePageChange(pagination.current + 1)}
                  disabled={pagination.current === Math.ceil(pagination.total / pagination.pageSize)}
                  className="pagination-btn"
                >
                  ›
                </button>
                <div className="pagination-jump">
                  <select
                    value={pagination.pageSize}
                    onChange={e => handlePageSizeChange(Number(e.target.value))}
                  >
                    {pageSizeOptions.map(size => (
                      <option key={size} value={size}>{size} 条/页</option>
                    ))}
                  </select>
                  <span>跳至</span>
                  <input
                    type="number"
                    min={1}
                    max={Math.ceil(pagination.total / pagination.pageSize)}
                    onKeyDown={e => {
                      if (e.key === "Enter") {
                        const page = Number(e.target.value);
                        if (page >= 1 && page <= Math.ceil(pagination.total / pagination.pageSize)) {
                          handlePageChange(page);
                        }
                      }
                    }}
                    placeholder="页码"
                  />
                  <span>页</span>
                </div>
              </div>
            </div>
          )}

          {/* 删除确认弹窗 */}
          {showDeleteModal && (
            <div className="modal-overlay" onClick={() => setShowDeleteModal(false)}>
              <div className="modal-content" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                  <h2>确认删除</h2>
                </div>
                <div className="modal-body">
                  <p>确定要删除该帖子吗？删除后不可恢复。</p>
                </div>
                <div className="modal-footer">
                  <button className="btn btn-outline" onClick={() => setShowDeleteModal(false)}>
                    取消
                  </button>
                  <button
                    className="btn btn-primary"
                    style={{ background: "#ff6699", border: "none" }}
                    onClick={handleDelete}
                  >
                    确认删除
                  </button>
                </div>
              </div>
            </div>
          )}

          {showLockModal && (
            <div className="lock-modal">
              <div className="lock-modal-content">
                <h3>确认锁定</h3>
                <p>你确定要锁定该帖子吗？</p>
                <div className="lock-modal-actions">
                  <button className="btn-confirm" onClick={confirmLock}>确认</button>
                  <button className="btn-cancel" onClick={() => {setShowLockModal(false); setLockId(null)}}>取消</button>
                </div>
              </div>
            </div>
          )}


        </div>
      </div>
    </div>
  );
}

export default PostManagement;